import Vue from 'vue'
import VueRouter from 'vue-router'
import {initUser} from '@/common/function'
import {cloneDeep} from 'lodash'
import Home from '@/views/main/home/Home'
import store from '@/store'

import settingManage from "@/router/settingManage";
import el from "element-ui/src/locale/lang/el";

Vue.use(VueRouter)

let initMenu = false

export const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/main/login/Login')
    }
]
export let mainRoutes;

export const childrenRoutes = [
    ...settingManage
]

const router = new VueRouter({
    routes
})
const withoutLoginUrl = ['Login']
router.beforeEach(async function (to, from, next) {
    if (/\/http/.test(to.path)) {
        let url = to.path.split('http')[1]
        window.location.href = `http${decodeURIComponent(url)}`
    } else {
        if (withoutLoginUrl.indexOf(to.name) > -1) {
            next()
        } else if (!store.getters.token) {
            await store.dispatch('_logout')
        } else if (!initMenu) {
            try {
                let childrenRoutes = await initUser()
                initMenu = true
                mainRoutes = {
                    path: '/',
                    name: 'Home',
                    component: Home,
                    meta: {
                        title: '首页',
                        affix: true,
                    },
                    children: [
                        {
                            path: '/redirect/:path*',
                            hidden: true,
                            meta: {
                                title: '',
                                withoutPermission: true,
                            },
                            component: () => import('@/views/main/redirect/redirect-index'),
                        },
                    ],
                }

                mainRoutes.children.push(...childrenRoutes)
                router.addRoute(mainRoutes)
                next({...to, replace: true})
            } catch (e) {
                console.log(e)
            }
        } else {
            if (to.fullPath.startsWith("/extra") && to.meta && to.meta.title) {
                document.title = to.meta.title
            }
            next()
        }
    }
})
export default router
